import 'package:flutter/material.dart';
import 'package:flutter_deer/account/iview/takeout_add_iview.dart';
import 'package:flutter_deer/account/models/user_bank_entity.dart';
import 'package:flutter_deer/account/presenter/takeout_add_presenter.dart';
import 'package:flutter_deer/account/widgets/withdraw_password_confirm.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/my_button.dart';
import 'package:flutter_deer/widgets/my_scroll_view.dart';
import 'package:flutter_deer/widgets/text_field_item.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:intl/intl.dart';

import '../account_router.dart';

class WithdrawalPage extends StatefulWidget {

  const WithdrawalPage({super.key,this.allowTakeOutScore});

  final double? allowTakeOutScore;

  @override
  _WithdrawalPageState createState() => _WithdrawalPageState();
}

class _WithdrawalPageState extends State<WithdrawalPage> with BasePageMixin<WithdrawalPage, PowerPresenter<dynamic>> implements TakeoutAddIMvpView {
  
  final TextEditingController _controller = TextEditingController();
  int _withdrawalType = 0;
  bool _clickable = false;
  UserBankEntity? _data;

  late TakeoutAddPresenter takeoutAddPresenter;

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    takeoutAddPresenter = new TakeoutAddPresenter();
    powerPresenter.requestPresenter([takeoutAddPresenter]);
    return powerPresenter;
  }

  @override
  void saveTakeoutSuccess(){
    NavigatorUtils.pushResult(context, AccountRouter.withdrawalResultPage,arguments: 1,(result) {
      NavigatorUtils.goBackWithParams(context,'success');
    });
  }

  @override
  void saveTakeoutFail(){
    NavigatorUtils.push(context, AccountRouter.withdrawalResultPage,arguments: 2);
  }
  
  @override
  void initState() {
    super.initState();
    _controller.addListener(verify);
  }

  @override
  void dispose() {
    _controller.removeListener(verify);
    _controller.dispose();
    super.dispose();
  }
  
  Future<void> verify() async {
    String price = _controller.text;
    if (_data==null||_data!.cardNo.nullSafe.isEmpty||price.isEmpty || double.parse(price.trim().replaceAll(',', '')) < 1||double.parse(price.trim().replaceAll(',', ''))>widget.allowTakeOutScore!) {
      setState(() {
        _clickable = false;
      });
      // return;
    }else {
      setState(() {
        _clickable = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        /// 拦截返回，关闭键盘，否则会造成上一页面短暂的组件溢出
        FocusManager.instance.primaryFocus?.unfocus();
        return Future.value(true);
      },
      child: Scaffold(
        appBar: MyAppBar(
          title: '${DeerLocalizations.of(context)!.withdrawal.nullSafe}',
        ),
        body: MyScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          children: <Widget>[
            Gaps.vGap5,
            InkWell(
              onTap: () {
                NavigatorUtils.pushResult(context, AccountRouter.userBankSelectPage, (result) {
                  setState(() {
                    _data = result as UserBankEntity;
                    verify();
                  });
                });
              },
              child: Container(
                width: double.infinity,
                height: 74.0,
                alignment: Alignment.center,
                child: _data==null?Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text('${DeerLocalizations.of(context)!.chooseBankCard.nullSafe}'),
                      Images.arrowRight
                    ]
                ):Row(
                  children: <Widget>[
                    CircleAvatar(
                      radius: 24.0,
                      backgroundColor: Colors.transparent,
                      backgroundImage: ImageUtils.getImageProvider(Constant.imageServerHost+'${_data!.cover}', holderImg: 'shop/tx'),
                    ),
                    Gaps.hGap16,
                    Expanded(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(_data!.bankName.nullSafe),
                          Gaps.vGap5,
                          Text(_data!.cardUsername.nullSafe, style: Theme.of(context).textTheme.titleSmall),
                          Gaps.vGap5,
                          Text(_data!.cardNo.nullSafe, style: Theme.of(context).textTheme.titleSmall),
                        ],
                      ),
                    ),
                    Images.arrowRight
                  ],
                ),
              ),
            ),
            Gaps.vGap16,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text('${DeerLocalizations.of(context)!.withdrawAmount.nullSafe}', style: TextStyles.textBold14),
                // Text('单笔2万，单日2万', style: TextStyle(fontSize: Dimens.font_sp12, color: Colours.orange))
              ],
            ),
            Gaps.vGap8,
            Row(
              children: <Widget>[
                Container(
                  width: 15.0,
                  height: 40.0,
                  padding: EdgeInsets.symmetric(vertical: 8.0),
                  child: LoadAssetImage('account/rmb', color: ThemeUtils.getIconColor(context),),
                ),
                Gaps.hGap8,
                Expanded(
                  child: TextField(
                    maxLength: 12,
                    controller: _controller,
                    keyboardType: const TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: [ThousandsFormatter()],
                    style: TextStyle(
                      fontSize: 32.0,
                      fontWeight: FontWeight.bold,
                      color: context.isDark==true?Colours.dark_text:Colours.text
                    ),
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.only(bottom: 8.0),
                      hintStyle: TextStyle(
                        fontSize: Dimens.font_sp14,
                        fontWeight: FontWeight.normal,
                        color: Colours.text_gray_c,
                      ),
                      hintText: '${DeerLocalizations.of(context)!.greaterThanNumberOne.nullSafe}',
                      counterText: '',
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ],
            ),
            Gaps.line,
            Gaps.vGap8,
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Visibility(visible: widget.allowTakeOutScore!>=0,child: Text('${DeerLocalizations.of(context)!.maxWithdrawableAmount.nullSafe}${NumberFormat.decimalPattern('en_us').format(widget.allowTakeOutScore)}', style: Theme.of(context).textTheme.titleSmall),),
                Visibility(visible: widget.allowTakeOutScore!<0.0,child: Text('${DeerLocalizations.of(context)!.noWithdrawableAmount.nullSafe}', style: Theme.of(context).textTheme.titleSmall)),
                Visibility(visible: widget.allowTakeOutScore!>=0,child: GestureDetector(
                    onTap: () {
                      _controller.text = '${NumberFormat.decimalPattern('en_us').format(widget.allowTakeOutScore)}';
                    },
                    child: SizedBox(
                      height: 48.0,
                      child: Text('${DeerLocalizations.of(context)!.allWithdrawals.nullSafe}', style: TextStyle(
                        fontSize: Dimens.font_sp12,
                        color: Theme.of(context).primaryColor,
                      )),
                    )
                ))
              ],
            ),
            Gaps.vGap24,
            MyButton(
              key: Key('提现'),
              onPressed: _clickable ? () {
                if(widget.allowTakeOutScore!>=0) {
                  showModalBottomSheet<bool>(
                      context: context,
                      /// 禁止拖动关闭
                      enableDrag: false,
                      /// 使用true则高度不受16分之9的最高限制
                      isScrollControlled: true,
                      builder: (_) => const WithdrawalPasswordConfirm()
                  ).then((result)=>{
                    if(result==true){
                      takeoutAddPresenter.saveTakeout(
                          _data!.bankId, _data!.cardNo.nullSafe,
                          _data!.cardUsername.nullSafe,
                          double.parse(_controller.text.trim().replaceAll(',', '').nullSafe))
                    }
                  });
                }
              } : null,
              text: '${DeerLocalizations.of(context)!.withdrawal.nullSafe}',
            ),
          ],
        ),
      ),
    );
  }
}
